const financialService = require('../../services/financial');

Page({
  data: {
    totalAssets: 0,
    totalProfit: 0,
    products: []
  },

  onLoad: function() {
    this.loadFinancialData();
  },

  onShow: function() {
    this.loadFinancialData();
  },

  // 加载理财产品数据
  async loadFinancialData() {
    wx.showLoading({
      title: '加载中...'
    });

    try {
      const products = await financialService.getFinancialList();
      let totalAssets = 0;
      let totalProfit = 0;

      products.forEach(product => {
        totalAssets += parseFloat(product.money || 0);
        totalProfit += parseFloat(product.profit || 0);
      });

      this.setData({
        products: products.map(product => ({
          id: product.id,
          name: product.name,
          currentValue: (parseFloat(product.money) + parseFloat(product.profit)).toFixed(2),
          totalProfit: parseFloat(product.profit).toFixed(2),
          annualizedReturn: product.arr.toFixed(2),
          type: product.type,
          bankId: product.bankId
        })),
        totalAssets: totalAssets.toFixed(2),
        totalProfit: totalProfit.toFixed(2)
      });
    } catch (error) {
      console.error('加载理财产品数据失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
    } finally {
      wx.hideLoading();
    }
  },

  // 跳转到产品详情页
  navigateToDetail: function(e) {
    const { id } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/financial/detail/detail?id=${id}`
    });
  },

  // 跳转到添加产品页
  navigateToAdd: function() {
    wx.navigateTo({
      url: '/pages/financial/add/add'
    });
  },

  // 计算年化收益率
  calculateAnnualizedReturn: function(buyAmount, currentValue, days) {
    if (days <= 0 || buyAmount <= 0) return 0;
    return (Math.pow(currentValue / buyAmount, 365 / days) - 1) * 100;
  }
}); 